//
//  XTManageCenter.swift
//  Kool Car
//
//  Created by huangweiqiang on 2021/12/15.
//

import UIKit
import Accelerate
import RxSwift
import HXPhotoPicker

class XTManageCenter {
    static let shared = XTManageCenter()
    
    public static func getPhoneAreaCodeList() -> [PhoneAreaObj] {
        let obj1 = PhoneAreaObj.init(name: "香港", code: "852")
        let obj2 = PhoneAreaObj.init(name: "大陆", code: "86")
        let obj3 = PhoneAreaObj.init(name: "澳门", code: "853")
        return [obj1, obj2, obj3]
    }
    
    public static var JPushAppKey = "2e528a594b3797791794ed06"//极光key
    public static let JPushChannel: String = "Publish channel"//l指明应用程序包的下载渠道，为方便分渠道统计，具体值由你自行定义，如：App Store。

    public static let JPushIsProduction: Bool = false//是否是生产环境
    public static let SearchHistoryTable:String = "SearchHistoryTable"  //历史搜索记录table
    public static let userId = "userId"//用户id
    public static let JpushMsgType = "JpushMsgType"//推送的类型处理
    public static let CartKey = "cartKey"//添加购物车准对游客如果是新用户第一次登陆，key可以为空，调用后会返回cartKey，之后用cartkey来识别未登录用户
    
    ///base64位 Decode
    public static func gtmBase64Decode(str: String) -> String {
        let result = (str as NSString).base64Decoded();
        return result ?? ""
    }
    
    ///base64位 encode
    public static func gtmBase64Encode(str: String) -> String {
        let result = (str as NSString).base64Encoded();
        return result ?? ""
    }
    
    ///获取启动页图片
    public static func getAppLaunchImageName() -> String {
        var launchImgName = "luanchImg"
        guard Bundle.main.infoDictionary!["UILaunchImages"] != nil else {
            return ""
        }
        let imgArr = Bundle.main.infoDictionary!["UILaunchImages"] as! NSArray
        //启动图
        if imgArr.count > 0 {
            for dict in imgArr {
                let tempDict = dict as! NSDictionary
                let imageSize = CGSizeFromString(tempDict["UILaunchImageSize"] as! String)
                if __CGSizeEqualToSize(imageSize, CGSize.init(width: kScreenWidth, height: kScreenHeight)) {
                    launchImgName = tempDict["UILaunchImageName"] as! String
                }
            }
        }
        return launchImgName
    }
    
    public static func getXTKeyWindow() -> UIWindow? {
        if #available(iOS 13.0, *) {
            var tempWindow: UIWindow!
            let windowList = UIApplication.shared.windows
            for kWindow in windowList.reversed() {
                if !kWindow.isKind(of: NSClassFromString("UITextEffectsWindow")!){
                    tempWindow = kWindow
                    break
                }
            }
            return tempWindow
        } else {
            return UIApplication.shared.keyWindow
        }
    }
    
    ///是否隐藏tabbar
    public static func willShowTabbar(isHidden: Bool){
//        guard let tabbarVC = UIApplication.shared.keyWindow?.rootViewController as? BaseTabbarController else {
//            return
//        }
        //tabbarVC.tabBar.isHidden = isHidden
    }
    
    ///判断是否是手机号  areaCode: 手机区号
    public static func judgeTextIsPhoneNumber(text: String, areaCode: String? = nil) -> Bool {
        var phoneArea = areaCode ?? XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.phoneCodeKey)
        phoneArea = phoneArea.replacingOccurrences(of: "+", with: "")
        switch phoneArea {
            case "852",
                "853":
                if text.count != 8 {
                    return false
                }
                
                let pwd =  "^(\\d{8})"
                let regextestpwd = NSPredicate(format: "SELF MATCHES %@",pwd)
                
                if (regextestpwd.evaluate(with: text) == false) {
                    //不全是数字，为非法手机号
                    return false
                }
                return true
            case "86":
                //默认86
                if text.count != 11 {
                    return false
                }
                let pwd =  "^(\\d{11})"
                let regextestpwd = NSPredicate(format: "SELF MATCHES %@",pwd)
                
                if (regextestpwd.evaluate(with: text) == false) {
                    //不全是数字，为非法手机号
                    return false
                }
                return true
            default:
                return true
        }
    }
    
    /**  保存String数据
     *
     * - Parameters:
     *   - key: 对应的key
     *   - value: 保存的数据
     */
    
    public static func setLocalDataString(aKey:String, aValue:String)  {
        let usrDefault = UserDefaults.standard
        usrDefault.setValue(aValue, forKey: aKey)
        usrDefault.synchronize()
    }
    
    /**  保存归档对像
     *
     * - Parameters:
     *   - key: 对应的key
     *   - value: 保存的数据
     */
    
    public static func setLocalDataObj(aKey:String, aValue: Any)  {
        let usrDefault = UserDefaults.standard
        let encodedObject = NSKeyedArchiver.archivedData(withRootObject: aValue)
        usrDefault.setValue(encodedObject, forKey: aKey)
        usrDefault.synchronize()
    }
    
    
    //保存数组
    public static func setLocalArrayObj(aKey: String, array: NSArray) {
        let archiverData = NSKeyedArchiver.archivedData(withRootObject: array)
        let usrDefault = UserDefaults.standard
        usrDefault.setValue(archiverData, forKey: aKey)
        usrDefault.synchronize()
    }
    
    ///获取本地缓存Data
    public static func getLocalDataObj(aKey:String) -> Any {
        let usrDefault = UserDefaults.standard
        let unarchiverData = usrDefault.value(forKey: aKey)
        if unarchiverData != nil {
            guard let getObj = try? NSKeyedUnarchiver.unarchiveObject(with: unarchiverData as! Data) else {
                fatalError("loadWidgetDataArray - Can't encode data")
            }
            //            let getObj = NSKeyedUnarchiver.unarchiveObject(with: unarchiverData as! Data)
            return getObj as Any
        }else {
            return NSMutableArray()
        }
        
    }
    
    
    
    /**  保存Bool数据
     *
     * - Parameters:
     *   - key: 对应的key
     *   - value: 保存的数据
     */
    public static func setLocalBool(aKey:String, aValue:Bool)  {
        let usrDefault = UserDefaults.standard
        usrDefault.setValue(aValue, forKey: aKey)
        usrDefault.synchronize()
    }
    
    /** 获取String数据
     *
     * - Parameters:
     *  - key: 对应的key
     *  - value: 保存的数据
     */
    public static func getLocalStringDataValue(aKey:String) ->(String)  {
        let usrDefault = UserDefaults.standard
        let tempValue = usrDefault.object(forKey: aKey)
        if tempValue != nil  {
            let strTemp:String = usrDefault.object(forKey: aKey) as! String
            return strTemp
        }else{
            return ""
        }
    }
    
    /** 获取Bool数据
     *
     * - Parameters:
     *  - key: 对应的key
     *  - value: 保存的数据
     */
    public static func getLocalBoolValue(aKey:String) ->(Bool)  {
        let usrDefault = UserDefaults.standard
        let tempValue = usrDefault.object(forKey: aKey)
        
        if tempValue != nil  {
            let strTemp:Bool = tempValue as! Bool
            return strTemp
        }else{
            return false
        }
    }
    
    /**
     *  获取document文件路径
     *
     *  @param folderPath 文件夹路径
     *
     *  @return
     */
    public static func documentsDirectory() ->String {
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let documentsDirectory = paths.first
        return documentsDirectory!
    }
    
    /**
     * 读取缓存大小
     */
    static func getAllCacheSize() -> String {
        return String(format: "%.2f",XTManageCenter.forderSizeAtPath(folderPath: NSHomeDirectory()))
    }
    
    /**
     * 清除缓存 自己决定清除缓存的位置
     */
    static func cleanCache(competion:()->Void) {
        //XTManageCenter.deleteFolder(path: NSHomeDirectory() + "/Documents")
        //XTManageCenter.deleteFolder(path: NSHomeDirectory() + "/Library")
        XTManageCenter.deleteFolder(path: NSHomeDirectory() + "/Library/WebKit")
        XTManageCenter.deleteFolder(path: NSHomeDirectory() + "/Library/Caches")
        XTManageCenter.deleteFolder(path: NSHomeDirectory() + "/tmp")
        competion()
    }
    
    
    /// 删除webkit
    ///
    /// - Parameter competion:
    static func clearWebKitCache() {
        XTManageCenter.deleteFolder(path: NSHomeDirectory() + "/Library/WebKit")
        //XTManageCenter.deleteFolder(path: NSHomeDirectory() + "/Library/Caches/com.koolcar.kuaima/WebKit")
    }
    
    
    /**
     * 删除单个文件
     */
    static func deleteFile(path: String) {
        let manage = FileManager.default
        do {
            try manage.removeItem(atPath: path)
        } catch {
            
        }
    }
    
    /**
     * 删除单个文件侠
     */
    static func deleteFolder(path: String) {
        let manage = FileManager.default
        if manage.fileExists(atPath: path) {
            let childFilePath = manage.subpaths(atPath: path)
            if (childFilePath != nil) {
                for path_1 in childFilePath! {
                    let fileAbsoluePath = path+"/"+path_1
                    XTManageCenter.deleteFile(path: fileAbsoluePath)
                }
            }
        }
    }
    
    /**
     * 计算单个文件的大小
     */
    static func returnFileSize(path:String) -> Double {
        let manager = FileManager.default
        var fileSize:Double = 0
        do {
            let attr = try manager.attributesOfItem(atPath: path)
            fileSize = Double(attr[FileAttributeKey.size] as! UInt64)
            let dict = attr as NSDictionary
            fileSize = Double(dict.fileSize())
        } catch {
            dump(error)
        }
        return fileSize/1024/1024
    }
    
    /**
     * 遍历所有子目录， 并计算文件大小
     */
    static func forderSizeAtPath(folderPath:String) -> Double {
        let manage = FileManager.default
        if !manage.fileExists(atPath: folderPath) {
            return 0
        }
        let childFilePath = manage.subpaths(atPath: folderPath)
        var fileSize:Double = 0
        for path in childFilePath! {
            let fileAbsoluePath = folderPath+"/"+path
            fileSize += XTManageCenter.returnFileSize(path: fileAbsoluePath)
        }
        return fileSize
    }
    
    
    /**
     * 保存图片到本地temp
     */
    public static func saveImage(data: NSData, imgName: String) -> String {
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        var documentsDirectory = paths.last //取到temp文件路径
        documentsDirectory = documentsDirectory?.replacingOccurrences(of: ".png", with: "")
        documentsDirectory?.append("/"+imgName+".png")
        data.write(toFile: documentsDirectory!, atomically: true)
        return documentsDirectory!
    }
    
    /**
     * 保文件到本地temp
     */
    public static func saveFile(data: NSData, fileName: String) -> String {
        var tempPath = NSHomeDirectory() + "/tmp"
        tempPath = String(format: "%@/%@", tempPath,fileName)
        let flag = data.write(toFile: tempPath, atomically: true)
        if flag {
            return tempPath
        }else{
            return ""
        }
    }
    
    /**
     * 获取temp路径
     */
    public static func getTempPath(fileName: String) -> String {
        var tempPath = NSHomeDirectory() + "/tmp"
        tempPath = String(format: "%@/%@", tempPath,fileName)
        return tempPath
    }
    
    /**
     * 获取temp路径
     */
    public static func getLocalImageDocumentDrectory(imgName: String) -> String {
        //let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        //var documentsDirectory = paths.last //取到temp文件路径
        var documentsDirectory = String(format: "%@", NSTemporaryDirectory())
        documentsDirectory = (documentsDirectory.replacingOccurrences(of: ".png", with: ""))
        documentsDirectory.append("/"+imgName+".png")
        return documentsDirectory
    }
    
    /**
     * 文件
     */
    public static func isFindFileTempDrectory(fileName: String) -> Bool {
        var documentsDirectory = String(format: "%@", NSTemporaryDirectory())
        documentsDirectory.append("/"+fileName)
        let flag = FileManager.default.fileExists(atPath: documentsDirectory)
        return flag
    }
    
    ///跳转登录页
    public func jumpToLoginView(animated:Bool? = true ,backHome: Bool? = false){
        let vc = LoginViewController()
        let navi = BaseNavigationController.init(rootViewController: vc)
        navi.modalPresentationStyle = .fullScreen
        if #available(iOS 13.0, *) {
            let window = UIApplication.shared.connectedScenes
                .filter({ $0.activationState == .foregroundActive })
                .map({ $0 as? UIWindowScene })
                .compactMap({ $0 })
                .last?.windows
                .filter({ $0.isKeyWindow })
                .last
            
            window?.rootViewController?.present(navi, animated: animated ?? true, completion: nil)
            self.backToHome(flag: backHome ?? false)
            
        } else {
            UIApplication.shared.keyWindow?.rootViewController?.present(navi, animated: animated ?? true, completion: nil)
            self.backToHome(flag: backHome ?? false)
        }
    }
    
    private func backToHome(flag: Bool){
        if flag {
            let tabbarVC = XTManageCenter.getXTKeyWindow()?.rootViewController as? BaseTabbarController
            Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { timer in
                let meNavi = tabbarVC?.childViewControllers.last as! BaseNavigationController
                meNavi.popToRootViewController(animated: false)
                tabbarVC?.selectedIndex = 0
            }
        }
    }
    
    /*
     * 计算label的高度
     */
    public static  func getLabHeight(labelStr:String,font:UIFont, width:CGFloat) -> CGFloat {
        let statusLabelText: String = labelStr
        let size = CGSize(width:width, height:5000)
        let dic = NSDictionary(object: font, forKey: kCTFontAttributeName as! NSCopying)
        let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedStringKey : Any] , context: nil).size
        return strSize.height + 1
    }
    
    /*
     * 计算label的宽度
     */
    public static  func getLabWidth(labelStr:String,font:UIFont,height:CGFloat) -> CGFloat {
        let statusLabelText: String = labelStr
        
        let size = CGSize(width:900, height:height)
        
        let dic = NSDictionary(object: font, forKey: kCTFontAttributeName as! NSCopying)
        
        let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedStringKey : Any] , context: nil).size
        return strSize.width + 1
    }
    
    /// 判断设备是否有摄像头
    ///
    /// - Returns:
    public static func isCameraAvailable() -> Bool {
        return UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
    }
    
    
    /// 后面的摄像头是否可用
    ///
    /// - Returns:
    public static func isRearCameraAvailable() -> Bool {
        return UIImagePickerController.isCameraDeviceAvailable(.rear)
    }
    
    
    /// 前面的摄像头是否可用
    ///
    /// - Returns:
    public static func isFrontCameraAvailable() -> Bool {
        return UIImagePickerController.isCameraDeviceAvailable(.front)
    }
    
    ///登录成功，关闭登录界面
    public func closeLoginPage(){
        let tempRootVC = XTManageCenter.getXTKeyWindow()
        let preVC = tempRootVC?.rootViewController?.presentedViewController
        if preVC != nil,
           let navi = preVC as? BaseNavigationController,
           ((navi.viewControllers.first as? LoginViewController) != nil) {
            navi.dismiss(animated: true) {
                print("已经关闭login")
                let tabbarVC = tempRootVC?.rootViewController as? BaseTabbarController
                let childs = tabbarVC?.childViewControllers ?? []
                var flag = false
                for kVC in childs {
                    let tempvcArray = (kVC as? BaseNavigationController)?.viewControllers ?? []
                    if tempvcArray.count > 0 {
                        
                        
                    }
                    if tempvcArray.count > 1  {
                        flag = true
                        break
                    }
                }
                if !flag {
                    XTManageCenter.willShowTabbar(isHidden: false)
                }
            }
        }
    }
    
    ///获取app当前语言
    /*
     zh-Hans: 简体（改变）
     zh-Hant: 繁体（改变）
     zh-HK: 香港繁体
     zh-MO: 澳门
     zh-TW: 台湾繁体（增加）
     */
    public static func getAppleLanguages() -> String {
        var tempStr = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.kAppLanguage)
        let verify = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.kAppVerify)
        if (verify == "1") {
            //app审核时默认繁体
            tempStr = AppLanguage.chinese_hk.rawValue
        }else if tempStr == "" {
//            let allLanguages = UserDefaults.standard.object(forKey: "AppleLanguages") as! NSArray
//            let curLan = allLanguages[0] as! String
//            if curLan.lowercased().contains("en") {
//                tempStr = AppLanguage.english.rawValue
//            }else if curLan == "zh-Hans" {
//                //简体
//                tempStr = AppLanguage.chinese_simple.rawValue
//            }else{
//                //繁体
                tempStr = AppLanguage.chinese_hk.rawValue
//            }
            XTManageCenter.setLocalDataString(aKey: UtilCenter.kAppLanguage, aValue: tempStr)  //默认简体
        }
        return tempStr
    }
    
    ///本地化语言 lauguage_zh    lauguage_hk   lauguage_en
    //    public func setLocalizable(){
    //        XTManageCenter.setLocalDataString(aKey: XTManageCenter.kAppLanguage, aValue: "lauguage_hk")
    //    }
    
    public static func callPhoneAction(phone: String) {
        if (phone == "") {
            UIApplication.shared.keyWindow?.rootViewController?.view.makeToast(message: "手机号码为空")
            return;
        }
        let timeArray = [MMLocalizedString("copy_phone", comment: "复制号码"), MMLocalizedString("call_phone", comment: "拨打电话")]
        //        let vc = MHActionSheetView()
        //        vc.modalPresentationStyle = .overFullScreen
        //        vc.titleStr = String(format: "%@", phone)
        //        vc.dataArray = timeArray
        //        UIApplication.shared.keyWindow?.rootViewController?.present(vc, animated: false, completion: nil)
        //        vc.callObjBack = { (_, tagIndex) in
        //            if tagIndex == 0 {
        //                UIPasteboard.general.string = phone
        //                UIApplication.shared.keyWindow?.rootViewController?.view?.makeToast(message: MMLocalizedString("copy_succeed", comment: "已复制"))
        //            }else{
        //                let phoneStr = String(format: "tel://%@", phone)
        //                if #available(iOS 10.0, *) {
        //                    UIApplication.shared.open(URL.init(string: phoneStr)!, options: [:], completionHandler: nil)
        //                } else {
        //                    UIApplication.shared.openURL(URL.init(string: phoneStr)!)
        //                }
        //            }
        //        }
    }
    
    
    ///密码由8-13数字和字母组合组成
    public static func isPassword(pasword : String) -> Bool {
        
        let pwd =  "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,13}$"
        
        let regextestpwd = NSPredicate(format: "SELF MATCHES %@",pwd)
        
        if (regextestpwd.evaluate(with: pasword) == true) {
            return true
        }else{
            return false
        }
        
    }
    
    
    ///取指定日期数据
    public static func getDateStringFormat(fromDateFormat: String, toDateFormat:String,  dateString: String) -> String {
        if dateString.removeAllSapce == "" {
            return ""
        }
        let dateFormat = DateFormatter()
        dateFormat.dateFormat = fromDateFormat
        let dateT = dateFormat.date(from: dateString.replacingOccurrences(of: "T", with: " "))
        if dateT == nil {
            return ""
        }
        let toDateF = DateFormatter()
        toDateF.dateFormat = toDateFormat
        let result  = toDateF.string(from: dateT!)
        return result
    }
    
    
    public static func calculateDateTimeFromNowBySecondAAA(ms: NSInteger) -> (String, String, String, String){
        let ss: NSInteger = 1
        let mi: NSInteger = ss * 60
        let hh: NSInteger = mi * 60
        let dd: NSInteger = hh * 24
        
        let day:NSInteger = NSInteger(ms/dd)
        let hour: NSInteger = (ms - (day * dd)) / hh
        let minute:NSInteger = (ms - day * dd - hour * hh) / mi;
        let second:NSInteger = (ms - day * dd - hour * hh - minute * mi) / ss
        
        ///
        var tempHour = "\(hour)"
        var tempMinute = "\(minute)"
        var tempSecond = "\(second)"
        if hour < 10 {
            tempHour = String(format: "0%ld", hour)
        }
        
        if minute < 10 {
            tempMinute = String(format: "0%ld", minute)
        }
        
        if second < 10 {
            tempSecond = String(format: "0%ld", second)
        }
        
        if day == 0 && hour == 0 && minute == 0 {
            return ("","","",tempSecond)
        }
        
        if day == 0 && hour == 0 {
            return ("","",String(format: "%@", tempMinute),tempSecond)
            
        }
        if day == 0  {
            return ("",String(format: "%@", tempHour),String(format: "%@", tempMinute),tempSecond)
        }
        return (String(format: "%@天", "\(day)"),String(format: "%@", tempHour),String(format: "%@", tempMinute),tempSecond)
    }
    
    
    
    
    /// 首页秒杀倒计时
    ///
    /// - Parameter ms:
    /// - Returns:
    public static func setDateFromNowBySecond(ms: NSInteger) -> String{
        let ss: NSInteger = 1
        let mi: NSInteger = ss * 60
        let hh: NSInteger = mi * 60
        let dd: NSInteger = hh * 24
        let mo: NSInteger = dd * 30
        let yy: NSInteger = mo * 12
        
        let day:NSInteger = NSInteger(ms/dd)
        let hour: NSInteger = (ms - (day * dd)) / hh
        let minute:NSInteger = (ms - day * dd - hour * hh) / mi
        let second:NSInteger = (ms - day * dd - hour * hh - minute * mi) / ss
        
        let moy:NSInteger = day * 30
        let yyyy:NSInteger = day * 30
        
        
        
        //        let milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss
        
        if day == 0 && hour == 0 && minute == 0 && second == 0 {
            return String(format: "00:00:00")
        }
        
        var temp_hour = String(format: "%d", hour)
        var temp_minute = String(format: "%d", minute)
        var temp_second = String(format: "%d", second)
        
        if day == 0 && hour == 0{
            if(minute < 10) {
                temp_minute = String(format: "0%d", minute)
            }
            if(second < 10){
                temp_second = String(format: "0%d", second)
            }
            return String(format: "00:%@:%@", temp_minute, temp_second)
        }
        
        
        if day == 0  {
            if(hour < 10) {
                temp_hour = String(format: "0%d", hour)
            }
            if(minute < 10){
                temp_minute = String(format: "0%d", minute)
            }
            if(second < 10){
                temp_second = String(format: "0%d", second)
            }
            return String(format: "%@:%@:%@", temp_hour, temp_minute, temp_second)
        }
        return String(format: "%@:%@:%@", temp_hour, temp_minute, temp_second)
    }
    
    
    
    ///获取公里
    public static func mileageUnit() ->String {
        return XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.kMileageUnit)
    }
    
    ///币 HK$
    public static func currentSign() -> String{
        return XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.kCurrencySign)
    }
    
    ///车制造年份
    public static func getCarCreateDate() -> [String] {
        let year = Date().getYear()
        var tempYearArr: [String] = []
        
        for tempYear in 1900...year {
            tempYearArr.append("\(tempYear)")
        }
        
        let spaceCount = 10 - tempYearArr.count % 10
        for _ in 0 ..< spaceCount {
            tempYearArr.insert("", at: 0)
        }
        
        return tempYearArr
    }
    
    ///前任车主数目
    public static func getCarOwersData() -> [String] {
        var tempYearArr: [String] = []
        for tempYear in 0...4 {
            tempYearArr.append("\(tempYear)")
        }
        return tempYearArr
    }
    
    /// 获取现在的日期
    ///
    /// - Returns:
    public static func getDateTimeStringNow(format: String? = "yyyy-MM-dd HH:mm:ss") -> String {
        //当前时间
        //当前时间
        let dateFormat = DateFormatter()
        dateFormat.dateFormat = format
        //        dateFormat.locale = Locale.current
        dateFormat.timeZone = TimeZone.init(identifier: "UTC")
        let datee = Date.init(timeIntervalSinceNow: 0)
        let zone = NSTimeZone.default
        
        let interval = zone.secondsFromGMT(for: datee)
        let currentDate = datee.addingTimeInterval(TimeInterval(interval))
        let str1 = dateFormat.string(from: currentDate)
        return str1
    }
    
    public static func getCurrentDate(format: String? = "yyyy-MM-dd HH:mm:ss") -> Date? {
        //当前时间
        //当前时间
        let dateFormat = DateFormatter()
        dateFormat.dateFormat = format
        dateFormat.locale = Locale.current
        dateFormat.timeZone = TimeZone.init(identifier: "UTC")
        let datee = Date.init(timeIntervalSinceNow: 0)
        let zone = NSTimeZone.default
        
        let interval = zone.secondsFromGMT(for: datee)
        let currentDate = datee.addingTimeInterval(TimeInterval(interval))
        return currentDate
    }
    
    ///时间距离现在是否相差10分钟  true: 10分钟内   false: 超过了10分钟
    public static func dateBetweenNowTenMinute(dateStr: String) -> Bool {
        let dateFormat = DateFormatter()
        dateFormat.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormat.locale = Locale.current
        dateFormat.timeZone = TimeZone.init(identifier: "GMT")
        guard let date = dateFormat.date(from: dateStr) else {
            return false
        }
        let interval = date.timeIntervalSinceNow - (8 * 60 * 60)
        if interval < -(10 * 60) {
            return true
        }
        return false
    }
    
    //判断是否为邮箱
    public static func isEmail(email: String) -> Bool{
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
        let emailTest: NSPredicate =  NSPredicate(format: "SELF MATCHES %@",emailRegex)
        return emailTest.evaluate(with: email)
    }
    
    
    
    ///label高度自适应
    /// - Parameters:
    ///   - text: 文字
    ///   - labelWidth: 最大宽度
    ///   - attributes: 字体，行距等
    /// - Returns: 高度
    public static func autoLabelHeight(with text:String , labelWidth: CGFloat ,attributes : [NSAttributedStringKey : Any]) -> CGFloat{
        var size = CGRect()
        let size2 = CGSize(width: labelWidth, height: 1000)//设置label的最大宽度
        size = text.boundingRect(with: size2, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes , context: nil);
        
        
        return size.size.height
    }
    
    
    ///label宽度自适应
    /// - Parameters:
    ///   - text: 文字
    ///   - labelWidth: 最大宽度
    ///   - attributes: 字体，行距等
    /// - Returns: 高度
    public static func autoLabelWidth(with text:String , labelWidth: CGFloat ,attributes : [NSAttributedStringKey : Any]) -> CGFloat{
        var size = CGRect()
        let size2 = CGSize(width: labelWidth, height: 1000)//设置label的最大宽度
        size = text.boundingRect(with: size2, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes , context: nil);
        
        return size.size.width
    }
    
    /**
     * 将字符串每隔数位用分割符隔开
     *
     * @param source 目标字符串
     * @param gap    相隔位数，默认为3
     * @param gap    分割符，默认为逗号
     * @return       用指定分隔符每隔指定位数隔开的字符串
     *
     */
    public static func showPriceInComma(source: String, gap: Int = 3, seperator: Character = ",") -> String {
        var temp = source
        var lastStr = ""
        if Double(temp) ?? 0 < 1000{//小于这个数的不需要分隔
            return temp
        }
        
        if temp.contains("."){//有小数点的
            let dataArray = temp.components(separatedBy: ".")
            temp = dataArray.first ?? ""
            lastStr = "." + (dataArray.last ?? "")
        }
        
        /* 获取目标字符串的长度 */
        let count = temp.count
        /* 计算需要插入的【分割符】数 */
        let sepNum = count / gap
        /* 若计算得出的【分割符】数小于1，则无需插入 */
        guard sepNum >= 1 else {
            return temp
        }
        /* 插入【分割符】 */
        for i in 1...sepNum {
            /* 计算【分割符】插入的位置 */
            let index = count - gap * i
            /* 若计算得出的【分隔符】的位置等于0，则说明目标字符串的长度为【分割位】的整数倍，如将【123456】分割成【123,456】，此时如果再插入【分割符】，则会变成【,123,456】 */
            guard index != 0 else {
                break
            }
            /* 执行插入【分割符】 */
            temp.insert(seperator, at: temp.index(temp.startIndex, offsetBy: index))
        }
        return temp + lastStr
    }
    
    
    
    class func getHtmlLocalScaleString(htmlStr: String) -> String {
        let formatWeb = """
                <!DOCTYPEhtml>
                    <html>
                    <head>
                        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"name="viewport">
                        <meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
                    </head>
                    <style type="text/css">
                        img{
                            display:inline-block;
                            max-width:100%@;
                        }
                    </style>
                     
                    <body>
                        %@
                    </body>
                    </html>
                """
        let tempStr = String(format: formatWeb,"%", htmlStr)
        return tempStr
    }
    
    
    //介绍 扫描说明  去掉h5标签
    public static func htmlIntroductionDel(htmlStr: String) -> String{
        var introductionStr = htmlStr
        var text: NSString!
        let scanner = Scanner.init(string: introductionStr)
        while scanner.isAtEnd == false {
            scanner.scanUpTo("<", into: nil)
            scanner.scanUpTo(">", into: &text)
            introductionStr = introductionStr.replacingOccurrences(of: String(format: "%@>", text ?? ""), with: "")
        }
        
        return introductionStr
    }
    
    
    /// 获取现在的日期
    ///
    /// - Returns:
    public static func getDateStringNow(format: String? = nil) -> String{
        //当前时间
        let dateFormat = DateFormatter()
        dateFormat.dateFormat = format ?? "yyyy-MM-dd"
        let datee = Date.init(timeIntervalSinceNow: 0)
        let str = dateFormat.string(from: datee)
        return str
    }
    
    
    /// - Parameters:
    ///   - view: 需要设置的控件
    ///   - corner: 哪些圆角
    ///   - radii: 圆角半径
    /// - Returns: layer图层
    public static func configRectCorner(view: UIView, corner: UIRectCorner, radii: CGSize) -> CALayer {
        let maskPath = UIBezierPath.init(roundedRect: view.bounds, byRoundingCorners: corner, cornerRadii: radii)
        let maskLayer = CAShapeLayer.init()
        maskLayer.frame = view.bounds
        maskLayer.path = maskPath.cgPath
        return maskLayer
    }
    
    
    
    ///
    /// - Parameter forrmat: 日期格式 返回与当间时间的时间戳
    public static func getTimeIntervalToDateSecondFromNow(formatter: String, dateString: String) -> NSInteger  {
        var tempCount = 0 as NSInteger
        if dateString.removeAllSapce == "" {
            return 0
        }
        let dateFormat = DateFormatter()
        dateFormat.dateFormat = formatter
        let dateT = dateFormat.date(from: dateString)
        if dateT == nil {
            tempCount = 0
        }
        
        let expireTimeInterval:TimeInterval = dateT!.timeIntervalSince1970
        let now = NSDate()//获取当前时间
        let currentTimeInterval: TimeInterval = now.timeIntervalSince1970 //当前时间的时间戳
        
        if (expireTimeInterval - currentTimeInterval > 0) {
            //说明没有过期 求出距离过期时间
            tempCount = NSInteger(expireTimeInterval - currentTimeInterval)
        }else{
            tempCount = 0
        }
        return tempCount
    }
    
    
    ///  用于活动 返回 00:00:00
    ///
    /// - Parameter ms:
    /// - Returns:
    public static func calculateDateTimeFromNowBySecond(ms: NSInteger) -> String{
        let ss: NSInteger = 1
        let mi: NSInteger = ss * 60
        let hh: NSInteger = mi * 60
        let dd: NSInteger = hh * 24
        
        let day:NSInteger = NSInteger(ms/dd)
        let hour: NSInteger = (ms - (day * dd)) / hh
        let minute:NSInteger = (ms - day * dd - hour * hh) / mi;
        let second:NSInteger = (ms - day * dd - hour * hh - minute * mi) / ss
        
        ///
        var tempHour = "\(hour)"
        var tempMinute = "\(minute)"
        var tempSecond = "\(second)"
        if hour < 10 {
            tempHour = String(format: "0%ld", hour)
        }
        
        if minute < 10 {
            tempMinute = String(format: "0%ld", minute)
        }
        
        if second < 10 {
            tempSecond = String(format: "0%ld", second)
        }
        
        if day == 0 && hour == 0 && minute == 0 {
            return String(format: "00:00:%@", tempSecond)
        }
        
        //        if day == 0 && hour == 0 {
        //            return String(format: "%@:%@", tempMinute, tempSecond)
        //        }
        if day == 0  {
            return String(format: "%@:%@:%@", tempHour, tempMinute, tempSecond)
        }
        let dayHour = day * 24
        let allHour = (Int(tempHour) ?? 0) + dayHour
//        return String(format: "%@:%@:%@", "\(allHour)", tempMinute, tempSecond)
                return String(format: "%d天:%@:%@:%@", day, tempHour, tempMinute, tempSecond)
    }
    
    
    //yyyy-MM-dd HH:mm:ss
    public static func getDateTimeByInterval(seconds: NSInteger) -> String  {
        let dateFomatter = DateFormatter.init(withFormat: "yyyy-MM-dd HH:mm:ss", locale: "UTC")
        let date = Date.init(timeIntervalSince1970: TimeInterval(seconds))
        let dateStr = dateFomatter.string(from: date)
        return dateStr
    }
    
    ///get now second
    public static func getNoeDateSecond() -> NSInteger  {
        let now = NSDate()//获取当前时间
        let currentTimeInterval: TimeInterval = now.timeIntervalSince1970 //当前时间的时间戳
        return NSInteger(currentTimeInterval)
    }
    
    //内容 扫描说明  去掉h5标签
    public static func getRichTextContent(content: String) -> String {
        var introductionStr = content
        var text: NSString!
        let scanner = Scanner.init(string: introductionStr)
        while scanner.isAtEnd == false {
            scanner.scanUpTo("<", into: nil)
            scanner.scanUpTo(">", into: &text)
            introductionStr = introductionStr.replacingOccurrences(of: String(format: "%@>", text ?? ""), with: "")
        }
        return introductionStr
    }
    
    //十天前
    public static func checkTimes(createDate: String) -> String{
        
        var timeTips = ""
//    let date = XTManageCenter.getDateStringFormat(fromDateFormat: "yyyy-MM-dd HH:mm:ss", toDateFormat: "yyyy-MM-dd HH:mm", dateString: createDate)
        let date = createDate
        timeTips = date
        
        let oldF = DateFormatter()
        oldF.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        guard let oldDate = oldF.date(from:createDate) else {
            return timeTips
        }
        let timeDiff = Date().timeIntervalSince(oldDate)
        
//        if timeDiff/60 < 1{
//            timeTips = MMLocalizedString("just_now", comment: "刚刚")
//            return timeTips
//        }
//
//        let mins = Int(timeDiff / 60)
//        if mins < 60{
//            timeTips="\(mins)" + MMLocalizedString("minute_ago", comment: "分钟前")
//            return timeTips
//        }
//
        let hours = Int(timeDiff / 3600)

//        if hours < 4{
//            timeTips="\(hours)" + MMLocalizedString("hours_ago", comment: "小时前")
//            return timeTips
//        }
//
//
        let hours1 = XTManageCenter.getDateStringFormat(fromDateFormat: "yyyy-MM-dd HH:mm:ss", toDateFormat: "HH:mm", dateString: createDate)
         
        if  hours < 24 {//四小时后
            timeTips = MMLocalizedString("today", comment: "今天") + " " + hours1
            return timeTips
        }
        
   
        let days = Int(timeDiff/3600/24)
        printLog("天" + "\(days)")
        if  days == 1{//昨天
            timeTips = MMLocalizedString("yesterday", comment: "昨天") + " " + hours1
            return timeTips
        }
        
//        if days == 2 {//前天
//            timeTips = MMLocalizedString("before_yesterday", comment: "前天") + " " + hours1
//            return timeTips
//        }
        
        //        if days > 3 && days<10{
        //            timeTips = "\(days)" + MMLocalizedString("day_ago", comment: "天前")
        //            return timeTips
        //        }
        
        timeTips = XTManageCenter.getDateStringFormat(fromDateFormat: "yyyy-MM-dd HH:mm:ss", toDateFormat: "yyyy-MM-dd HH:mm", dateString: createDate)
        return timeTips
        
        //        let months = Int(timeDiff/3600/24/30)
        //        if months<12{
        //            timeTips="\(months)月前"
        //            return timeTips
        //        }
        //
        //        let years = Int(timeDiff/3600/24/30/12)
        //        timeTips="\(years)年前"
        //        return timeTips
        
        
    }
    
    
    //计算按钮宽高度
    public static func countBtnWidth(btn: UIButton) -> CGFloat{
        let size = btn.titleLabel?.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: 7000)) ?? CGSize.zero
        return size.width
    }
    
    ///本地参数，防止参数接口为空时用
    public static func setLocalPlaceParameter(paramData: ParameterDataModel? = nil) {
        if paramData != nil {
            
            XTManageCenter.setLocalDataString(aKey: UtilCenter.kCurrencySign, aValue: paramData?.currencySign ?? "")
            XTManageCenter.setLocalDataString(aKey: UtilCenter.kMileageUnit, aValue: paramData?.mileageUnit ?? "")
        }else{
            let jsonStr = "{\"code\":\"1\",\"msg\":\"ok\",\"data\":{\"currencySign\":\"HK$\",\"mileageUnit\":\"公裏\",\"areacodeList\":[{\"areacode\":\"+86\",\"order\":\"1\"}]}}"
            let jsonObj = BaseParameterModel.init(JSONString: jsonStr, context: nil)
            XTManageCenter.setLocalDataString(aKey: UtilCenter.kCurrencySign, aValue: jsonObj?.data?.currencySign ?? "")
            XTManageCenter.setLocalDataString(aKey: UtilCenter.kMileageUnit, aValue: jsonObj?.data?.mileageUnit ?? "")
        }
    }
    
    /**
     // 中文简体
     case simplifiedChinese = 1
     // 中文繁体
     case traditionalChinese = 2
     // 英文
     case english = 5
     */
    public static func getHXPhotoPickerLanguage() -> HXPhotoPicker.LanguageType {
        let language = XTManageCenter.getAppleLanguages()
        if language == "lauguage_en" {
            return HXPhotoPicker.LanguageType.english
        }else{
            return HXPhotoPicker.LanguageType.traditionalChinese
        }
    }
   
    /// 获取现在的日期时间 "yyyy-MM-dd HH:mm:ss"
    ///
    /// - Returns:
    public static func getDateTimeNowByFormater(formater: String) -> String{
        let dateFormat = DateFormatter()
        dateFormat.dateFormat = formater
        let datee = Date.init(timeIntervalSinceNow: 0)
        let str = dateFormat.string(from: datee)
        return str
    }
    ///获取某天后日期列表
    public static func getDateListDistanceDate(date: String, days: NSInteger) -> [String] {
        let tempDateFormatter = DateFormatter()
        tempDateFormatter.dateFormat = "yyyy-MM-dd"
        let calendar = Calendar.current
        var today: Date?
        if let tempDate = tempDateFormatter.date(from: date) {
            today = tempDate
        }else{
            today = Date()
        }
        
        var dateComponents = DateComponents()
        if days > 0 {
            dateComponents.day = 1
        }else{
            dateComponents.day = -1
        }
        var resultArray: [String] = []
        
        for _ in 1...abs(days) {
            guard let nextDate = calendar.date(byAdding: dateComponents, to: today!) else {
                break
            }
           
            let tempDateStr = tempDateFormatter.string(from: nextDate)
            resultArray.append(tempDateStr)
            today = nextDate
        }
        return resultArray
    }
    
    ///服务-获取跟离当天多少天后的日期列表 [2023-01-01, 2023-01-02]
//    public static func getDateListDistanceNow(days: NSInteger) -> [String] {
//        let calendar = Calendar.current
//        var today = Date()
//        var dateComponents = DateComponents()
//        if days > 0 {
//            dateComponents.day = 1
//        }else{
//            dateComponents.day = -1
//        }
//        var resultArray: [String] = []
//
//        for _ in 1...abs(days) {
//            guard let nextDate = calendar.date(byAdding: dateComponents, to: today) else {
//                break
//            }
//            let tempDateFormatter = DateFormatter()
//            tempDateFormatter.dateFormat = "yyyy-MM-dd"
//            let tempDateStr = tempDateFormatter.string(from: nextDate)
//            resultArray.append(tempDateStr)
//            today = nextDate
//        }
//        return resultArray
//    }
    
    ///服务-获取跟离当天多少天后的月份列表  [2023-01, 2023-02]
    public static func getMonthsListDistanceNow(days: NSInteger) -> [String] {
        let calendar = Calendar.current
        var date = Date()
        var months = Set<String>()
        for _ in 1...days {
            date = calendar.date(byAdding: .day, value: 1, to: date)!
            let dateForm = DateFormatter()
            dateForm.dateFormat = "yyyy-MM"
            let tempDateStr = dateForm.string(from: date)
            months.insert(tempDateStr)
        }
        return Array(months).sorted(by: {$0 < $1})
    }
    
    ///服务-获取跟离当天多少天后日期String 如 20234-10-10
    public static  func getDateDistanceNow(days: NSInteger) -> String {
        let calendar = Calendar.current
        var date = Date()
        date = calendar.date(byAdding: .day, value: days, to: date)!
        let dateForm = DateFormatter()
        dateForm.dateFormat = "yyyy-MM-dd"
        let tempDateStr = dateForm.string(from: date)
        return tempDateStr
    }
    
    
    ///获取日期所在的周的起始日期
    public static func getCurrentDateInWeekStart(date: String) -> String {
        let dateForm = DateFormatter()
        dateForm.dateFormat = "yyyy-MM-dd"
        guard let currentDate = dateForm.date(from: date) else {
            return ""
        }
        
        let calendar = Calendar.current
        // 获取当前日期所在周的开始日期
        let components = calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: currentDate)
        guard let startOfWeekDate = calendar.date(from: components) else { return "" }
        return dateForm.string(from: startOfWeekDate)
    }
    
    ///获取日期所在的周的日期列表[2020-02-02, 2020-02-02]
    public static func getCurrentWeeks(date: String) -> [String] {
        let dateForm = DateFormatter()
        dateForm.dateFormat = "yyyy-MM-dd"
        guard let currentDate = dateForm.date(from: date) else {
            return []
        }
        
        let calendar = Calendar.current
        // 获取当前日期所在周的开始日期
        let components = calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: currentDate)
        guard let startOfWeekDate = calendar.date(from: components) else { return [] }

        var resultArray: [String] = []
        var dateComponents = DateComponents()
        dateComponents.day = 1
        for pIndex in 0...6 {
            dateComponents.day = pIndex
            guard let nextDate = calendar.date(byAdding: dateComponents, to: startOfWeekDate) else {
                break
            }
            let tempDateFormatter = DateFormatter()
            tempDateFormatter.dateFormat = "yyyy-MM-dd"
            let tempDateStr = tempDateFormatter.string(from: nextDate)
            resultArray.append(tempDateStr)
        }
        
        return resultArray
    }
    
    ///  支付订单与订单详情用 返回 00:00:00
    ///
    /// - Parameter ms:
    /// - Returns:
    public static func calculateDateTimeFromNowBySecondaa(ms: NSInteger) -> String{
        let ss: NSInteger = 1
        let mi: NSInteger = ss * 60
        let hh: NSInteger = mi * 60
        let dd: NSInteger = hh * 24
        
        let day:NSInteger = NSInteger(ms/dd)
        let hour: NSInteger = (ms - (day * dd)) / hh
        let minute:NSInteger = (ms - day * dd - hour * hh) / mi;
        let second:NSInteger = (ms - day * dd - hour * hh - minute * mi) / ss
        
        ///
        var tempHour = "\(hour)"
        var tempMinute = "\(minute)"
        var tempSecond = "\(second)"
        if hour < 10 {
            tempHour = String(format: "0%ld", hour)
        }
        
        if minute < 10 {
            tempMinute = String(format: "0%ld", minute)
        }
        
        if second < 10 {
            tempSecond = String(format: "0%ld", second)
        }
        
        if day == 0 && hour == 0 && minute == 0 {//只有秒
            return String(format: "00:%@", tempSecond)
        }
        
        if day == 0 && hour == 0 {//分秒
            return String(format: "%@:%@", tempMinute, tempSecond)
        }
        if day == 0  {//时分秒
            return String(format: "%@:%@:%@", tempHour, tempMinute, tempSecond)
        }
        return String(format: "%d天:%@:%@:%@", day, tempHour, tempMinute, tempSecond)
    }
    
    /// 计算距现在还有多长时间 Interval
    ///
    /// - Parameter time: 2018-08-29 09:44:28
    /// - Returns:
    public static func getTimeFromNowSecond(time: String) -> NSInteger{
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let expireDate = dateFormatter.date(from: time)
        let seconds = expireDate?.timeIntervalSinceNow
        return NSInteger(seconds ?? 0)
    }
    
    
    //电话号码或者邮箱除前三位和后四位，其它打星号
    public static func getAsterisk(text: String) -> String{
        let firstThree = text.prefix(3)
        let lastFour = text.suffix(4)
        let middle = String(repeating: "*", count: text.count - 7)
        let content = "\(firstThree)\(middle)\(lastFour)"
        return content
    }
    
    ///获取优惠券使用场景
    public static func getCouponuByscene(useScene: String) -> String {
        var tempStr = ""
        if useScene == "1" {
            tempStr = "只适用于商城产品"
        } else if useScene == "2" {
            tempStr = "只适用于汽车服"
        } else if useScene == "1,2" || useScene == "2,1"{
            tempStr = "可用于商城产品或汽车服务"
        }
        return tempStr
    }
    
    
    /// JWT base64解码
    ///
    /// - Parameter dataString:
    /// - Returns:
    public static func jwtDecode(dataString: String)->[String: Any]{
        if dataString.removeAllSapce == "" {
            return [:]
        }
        /**分割为数组*/
        let segments = dataString.components(separatedBy: ".")
        /**获取第二个元素Payload负载元素(有意义的key就在里面解析的)*/
        var base64String = segments[1]
        /** base64解码*/
        let requiredLength = (4 * ceil((Float)(base64String.count)/4.0))
        let nbrPaddings = Int(requiredLength) - base64String.count
        if nbrPaddings > 0 {
            let pading = "".padding(toLength: nbrPaddings,withPad: "=",startingAt: 0)
            base64String = base64String + pading
        }
        base64String = base64String.replacingOccurrences(of: "-",with: "+")
        base64String = base64String.replacingOccurrences(of: "_",with: "/")
        let decodeData = Data(base64Encoded: base64String,options: Data.Base64DecodingOptions.ignoreUnknownCharacters)
        let decodeString = String.init(data: decodeData!,encoding: String.Encoding.utf8)
        /**转为字典*/
        let jsonDict:[String : Any]? = try? JSONSerialization.jsonObject(with:(decodeString?.data(using: String.Encoding.utf8))!,options: JSONSerialization.ReadingOptions.mutableContainers)as![String : Any]
        /**返回jwt */
        return jsonDict ?? [:]
    }
    
    
    
    /// base64解码
    ///
    /// - Parameter dataString:
    /// - Returns:
    public static func base64Decoding(dataString: String) -> Any{
        let decodedData = Data.init(base64Encoded: dataString, options: Data.Base64DecodingOptions.init(rawValue: 0))
        if decodedData != nil  {
            let jsonString = NSString(data: decodedData! as Data, encoding: String.Encoding.utf8.rawValue)! as String
            
            let jsonData = jsonString.data(using: String.Encoding.utf8, allowLossyConversion: false) ?? Data()
            guard let json =
                try?
                    JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
                else {
                    return ""
            }
            return json
        }
        return NSDictionary.init()
        
    }
    
}
